#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
消息数据访问对象 (DAO)
严格遵循DAO层职责：仅负责数据库CRUD操作，不包含任何业务逻辑
"""

from typing import List, Dict, Any, Optional
from datetime import datetime
import uuid
from models.message import Message
from models.base import db
from settings import get_logger
from utils.enum.message_enum import MessageTypeEnum, MessageDirectionEnum, ChatTypeEnum

class MessageDAO:
    """
    消息数据访问对象
    
    职责：
    - 执行消息表的CRUD操作
    - 保存消息记录
    - 查询消息记录
    - 不包含任何业务逻辑或数据验证
    """
    
    def __init__(self):
        """
        初始化DAO
        """
        self.logger = get_logger(__name__)
    
    def save_message(self, message_data: Dict[str, Any]) -> str:
        """
        保存消息记录
        
        Args:
            message_data: 消息数据字典
            
        Returns:
            新插入消息的ID
        """
        try:
            message_id = str(uuid.uuid4())
            self.logger.info(f"保存消息记录: {message_data.get('content', '')[:30]}...")
            
            # 使用枚举类转换消息类型、方向和聊天类型
            msg_type_str = message_data.get('message_type', 'text')
            msg_type_int = MessageTypeEnum.from_str(msg_type_str)
                
            # 将方向从字符串转换为枚举值
            direction_str = message_data.get('direction', 'sent')
            direction_int = MessageDirectionEnum.from_str(direction_str)
                
            # 确定聊天类型
            chat_type_str = message_data.get('chat_type', 'private')
            chat_type_int = ChatTypeEnum.from_str(chat_type_str)
                
            message = Message(
                id=message_id,
                account=message_data.get('account', 'default'),  # 使用默认账号
                sender_name=message_data.get('sender', 'self'),
                receiver_name=message_data.get('receiver', ''),
                content=message_data.get('content', ''),
                message_type=msg_type_int,
                chat_type=chat_type_int,
                direction=direction_int,
                status=message_data.get('status', 'sent'),
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            
            db.session.add(message)
            db.session.commit()
            self.logger.info(f"成功保存消息记录，ID: {message_id}")
            return message_id
            
        except Exception as e:
            self.logger.error(f"保存消息记录失败: {e}")
            import traceback
            self.logger.error(traceback.format_exc())
            db.session.rollback()
            raise
    
    def save_auto_reply(self, auto_reply_data: Dict[str, Any]) -> str:
        """
        保存自动回复记录
        
        Args:
            auto_reply_data: 自动回复数据字典
            
        Returns:
            新插入自动回复的ID
        """
        try:
            message_id = str(uuid.uuid4())
            self.logger.info(f"保存自动回复记录: {auto_reply_data.get('reply_content', '')[:30]}...")
            
            # 使用枚举类转换消息类型
            msg_type_str = auto_reply_data.get('message_type', 'text')
            msg_type_int = MessageTypeEnum.from_str(msg_type_str)
                
            # 保存原始消息
            original_message = Message(
                id=str(uuid.uuid4()),
                account=auto_reply_data.get('account', 'default'),
                sender_name=auto_reply_data.get('sender', ''),
                receiver_name=auto_reply_data.get('receiver', 'self'),
                content=auto_reply_data.get('original_content', ''),
                message_type=msg_type_int,
                chat_type=ChatTypeEnum.PRIVATE,  # 私聊
                direction=MessageDirectionEnum.RECEIVED,  # 接收
                status='success',
                is_processed=True,  # 已处理
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            
            # 保存回复消息
            reply_message = Message(
                id=message_id,
                account=auto_reply_data.get('account', 'default'),
                sender_name=auto_reply_data.get('receiver', 'self'),  # 接收者变为发送者
                receiver_name=auto_reply_data.get('sender', ''),  # 发送者变为接收者
                content=auto_reply_data.get('reply_content', ''),
                message_type=msg_type_int,
                chat_type=ChatTypeEnum.PRIVATE,  # 私聊
                direction=MessageDirectionEnum.SENT,  # 发送
                status='success',
                is_auto_reply=True,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            
            db.session.add(original_message)
            db.session.add(reply_message)
            db.session.commit()
            self.logger.info(f"成功保存自动回复记录，ID: {message_id}")
            return message_id
            
        except Exception as e:
            self.logger.error(f"保存自动回复记录失败: {e}")
            import traceback
            self.logger.error(traceback.format_exc())
            db.session.rollback()
            raise
    
    def get_messages_by_sender_receiver(self, sender: str, receiver: str, limit: int = 50) -> List[Message]:
        """
        根据发送者和接收者查询消息记录
        
        Args:
            sender: 发送者
            receiver: 接收者
            limit: 返回记录数量限制
            
        Returns:
            消息记录列表
        """
        try:
            messages = Message.query.filter(
                ((Message.sender_name == sender) & (Message.receiver_name == receiver)) |
                ((Message.sender_name == receiver) & (Message.receiver_name == sender))
            ).order_by(Message.created_at.desc()).limit(limit).all()
            
            return messages
            
        except Exception as e:
            self.logger.error(f"查询消息记录失败: {e}")
            import traceback
            self.logger.error(traceback.format_exc())
            return []
    
    def get_messages_by_direction(self, direction: str, limit: int = 50) -> List[Message]:
        """
        根据消息方向查询消息记录
        
        Args:
            direction: 消息方向 (sent 或 received)
            limit: 返回记录数量限制
            
        Returns:
            消息记录列表
        """
        try:
            # 使用枚举类转换消息方向
            direction_int = MessageDirectionEnum.from_str(direction)
                
            messages = Message.query.filter(
                Message.direction == direction_int
            ).order_by(Message.created_at.desc()).limit(limit).all()
            
            return messages
            
        except Exception as e:
            self.logger.error(f"查询消息记录失败: {e}")
            import traceback
            self.logger.error(traceback.format_exc())
            return []
    
    def get_auto_replies(self, limit: int = 50) -> List[Message]:
        """
        查询自动回复消息记录
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            自动回复消息记录列表
        """
        try:
            messages = Message.query.filter(
                Message.is_auto_reply == True
            ).order_by(Message.created_at.desc()).limit(limit).all()
            
            return messages
            
        except Exception as e:
            self.logger.error(f"查询自动回复记录失败: {e}")
            import traceback
            self.logger.error(traceback.format_exc())
            return []